package com.hu.bgp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Deze heet JarClassLoader omdat ie ooit rechtstreeks uit een .jar klassen moet
 * kunnen laden. Maar hij kan nu alleen uit een File of InputStream klassen
 * laden.
 * 
 * @author ejvos
 */
public final class JarClassLoader extends ClassLoader
{
	public JarClassLoader()
	{
		super(JarClassLoader.class.getClassLoader());
	}

	public Class<?> loadFromFile(String name, File file) throws ClassNotFoundException
	{
		try
		{
			InputStream stream = new FileInputStream(file);
			int length = (int) file.length();
			Class<?> result = loadFromInputStream(name, stream, length);
			try
			{
				stream.close();
			}
			catch (IOException e)
			{
				// ignored
			}
			return result;
		}
		catch (Throwable t)
		{
			throw new ClassNotFoundException(t.getMessage(), t);
		}
	}

	public Class<?> loadFromInputStream(String name, InputStream stream, int length) throws ClassNotFoundException
	{
		try
		{
			Class<?> c = null;
			byte[] bytes = new byte[length];
			int length2 = stream.read(bytes, 0, length);
			c = defineClass(name, bytes, 0, length2);
			return c;
		}
		catch (Throwable t)
		{
			throw new ClassNotFoundException(t.getMessage(), t);
		}
	}
}